<template>
    <el-card>
        <div>
            <div>
                <img v-if="qrContent" id="loginQrCode" ref="loginQrCodeRef"
                     :src="`/api/qr/generate/loginQrCode?content=${qrContent}`" :alt="qrContent">
            </div>
            <div>二维码当前状态:{{ qrStatus }}</div>
            <div>
                <el-button type="primary" @click="qrcodeParser">模拟扫码</el-button>
                <el-button type="warning" @click="confirmLogin">确认登录</el-button>
            </div>
        </div>
    </el-card>
</template>
<script setup>
import {nanoid} from "nanoid";
import QrcodeDecoder from 'qrcode-decoder';
import {inject, ref, onMounted} from 'vue'
import {confirmLoginQrCodeApi, scanLoginQrCodeApi, verifyLoginQrCodeApi} from "@/api/business/qrCode.js";

const qr = new QrcodeDecoder();
const qrStatus = ref("未扫码")
const loginQrCodeRef = ref();
const goEasy = inject("goEasy")
const qrContent = ref();
const mbKey = ref("")
const timer = ref(null)
goEasy.subscribe("loginQrCode").then(res => {
    console.log(res)
    const content = res.content;
    qrStatus.value = content;
    if (content === "已扫描,待确认") {
        // 轮询校验接口
        // verifyLoginQrCode()
    }
})
onMounted(() => {
    qrContent.value = nanoid();
})

/**
 * 模拟扫描登录二维码 mb
 */
const qrcodeParser = () => {
    qr.decodeFromImage(document.querySelector("#loginQrCode")).then((res) => {
        scanLoginQrCodeApi(res.data).then(res => {
            console.log(res)
            mbKey.value = res.data
            verifyLoginQrCode()

        })
    });
}

/**
 * 确认登录二维码 mb
 */
const confirmLogin = () => {
    confirmLoginQrCodeApi(mbKey.value).then(res => {
        console.log(res)
    })
}
/**
 * 校验登录二维码 pc
 */
const verifyLoginQrCode = () => {
    timer.value = setInterval(() => {
        verifyLoginQrCodeApi(mbKey.value).then(res => {
            console.log(res)
            qrStatus.value = res.msg
            if (res.msg === "登录成功") {
                clearInterval(timer.value)
                timer.value = null;
            }
        })
    }, 1000 * 3)
}
// goEasy.publish("test","哈哈哈我来了")
</script>
<style></style>
